package com.laoli.service.impl;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.laoli.entity.EduConstant;
import com.laoli.entity.User;
import com.laoli.entity.UserDTO;
import com.laoli.mapper.UserMapper;
import com.laoli.service.UserService;
import com.laoli.utils.JWTUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;

import java.util.Date;
import java.util.Map;
import java.util.concurrent.TimeUnit;
/**
 * Created with IntelliJ IDEA.
 *
 * @Author: lfw
 * @Date: 2022/04/04/18:54
 * @Description:
 */
@Service
public class UserServiceImpl implements UserService {
    @Autowired
    private UserMapper userMapper;
    @Autowired
    private RedisTemplate redisTemplate;
    @Override
    public UserDTO login(String phone, String password) {
        UserDTO dto=new UserDTO();
        QueryWrapper<User> queryWrapper=new QueryWrapper<>();
        queryWrapper.eq("phone",phone);
        Integer integer = userMapper.selectCount(queryWrapper);
        if(integer==0){
            dto.setState(EduConstant.ERROR_NOT_FOUND_PHONE_CODE);
            dto.setMessage(EduConstant.ERROR_NOT_FOUND_PHONE);
        }
        else {
            queryWrapper.eq("password",password);
            User user = userMapper.selectOne(queryWrapper);
            if(user==null){//登录失败
                dto.setState(EduConstant.ERROR_PASSWORD_CODE);
                dto.setMessage(EduConstant.ERROR_PASSWORD);
            }
            else {//登录成功
                dto.setState(EduConstant.LOGIN_SUCCESS_CODE);
                dto.setMessage(EduConstant.LOGIN_SUCCESS);
            }
            //生成token
            String token = JWTUtils.createToken(user);
            //保存到redis中
            redisTemplate.opsForValue().set(token,token,15*1000, TimeUnit.SECONDS);
            dto.setToken(token);
        }
        return dto;
    }
    //检验token
    @Override
    public UserDTO checkToken(String token) {
        UserDTO userDTO=new UserDTO();
        Map<String, Object> map = JWTUtils.checkToken(token);
        //校验通过
        if(map!=null){
            userDTO.setState(EduConstant.TOKEN_SUCCESS_CODE);
            userDTO.setMessage(EduConstant.TOKEN_SUCCESS);
            //校验通过，重新设置token过期时间
            redisTemplate.opsForValue().set(token,token,600 , TimeUnit.SECONDS);
            System.out.println(token);
        }
        else {
            userDTO.setState(EduConstant.TOKEN_ERROR_CODE);
            userDTO.setMessage(EduConstant.TOKEN_ERROR2);
        }
        return userDTO;
    }
    /*
    * 注册用户
    * */
    @Override
    public Integer register(String phone, String password, String nickname, String headimg) {
        User user=new User();
        user.setPhone(phone);
        user.setPassword(password);
        user.setName(nickname);
        user.setPortrait(headimg);
        return userMapper.insert(user);
    }
}
